<?php

namespace app\job\queue;

use app\admin\model\system\Notify as SystemNotify;
use think\facade\Log;
use think\facade\Queue;
use think\queue\Job;
use app\common\enum\SystemNotifyStatusEnum;
use app\job\queue\ImSendMessageJob;

class SystemNotifyJob
{
    public function fire(Job $job, $data)
    {
        // 记录任务开始日志
        Log::channel('job')->info('SystemNotifyJob started with data: ' . json_encode($data));

        if ($job->attempts() > 3) {
            // 任务重试次数超过3次，标记为失败并删除任务
            Log::channel('job')->warning('SystemNotifyJob failed after 3 attempts');
            $job->failed($data);
            $job->delete();
            return;
        }

        try {
            // 准备要插入的数据
            foreach ($data['user_ids'] as $index => $user_id) {
                $insertData = [
                    'queue_id' => $data['queue_id'],
                    'user_id' => $user_id,
                    'push_status' => SystemNotifyStatusEnum::PUSHING->value,
                    'title' => $data['title'],
                    'content' => $data['content'],
                    'type' => $data['type']
                ];
                SystemNotify::create($insertData);
                // 拆任务发IM消息
                Queue::push(ImSendMessageJob::class, $insertData, 'ImSendMessageJob');
                
                // 控制速率，每分钟最多运行200次
                if (($index + 1) % 200 === 0) {
                    sleep(60); // 暂停1分钟
                }
                // 每次循环延时，分散请求，1分钟内总延时不超过60秒
                usleep((int)(60 / 200 * 1000000)); // 延时300毫秒
            }


            // 删除rabbitmq队列
            $job->delete();

        } catch (\Throwable $e) {
            // 记录错误日志
            Log::channel('job')->error('Error processing SystemNotifyJob: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            throw $e;
        }
    }

    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
        custom_log(json_encode($data, 256), null, 'failed_job');
    }
}